package com.test.task;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * 线程池服务类. <br>
 * 线程池服务.
 * <p>
 * Copyright: Copyright (c) Nov 22, 2010 3:10:19 PM
 * <p>
 * Company: 北京宽连十方数字技术有限公司
 * <p>
 * 
 * @author suncg@c-platform.com
 * @version 1.0.0
 */
public class ThreadPoolService {

	/**
	 * 默认线程池大小
	 */
	public static final int DEFAULT_POOL_SIZE = 10;

	/**
	 * 一个任务的默认超时时间 毫秒
	 */
	public static final long DEFAULT_TASK_TIMEOUT = 1000L;

	private int poolSize = DEFAULT_POOL_SIZE;

	private ExecutorService executorService;

	/**
	 * 采用默认大小线程池
	 */
	public ThreadPoolService() {
	}

	/**
	 * 指定线程池大小
	 * 
	 * @param poolSize
	 *            线程池大小
	 */
	public ThreadPoolService(int poolSize) {
		this.poolSize = poolSize;
	}

	public void execute(Runnable task) {
		executorService.execute(task);
	}

	/**
	 * 销毁服务
	 * 
	 * @param timeout
	 *            超时时间 毫秒
	 */
	public void destoryService(long timeout) {
		if (executorService != null && !executorService.isShutdown()) {
			try {
				executorService.awaitTermination(timeout, TimeUnit.MILLISECONDS);
			}
			catch (InterruptedException e) {
				e.printStackTrace();
			}
			executorService.shutdown();
		}
	}

	/**
	 * 创建服务 1.关闭存活的服务 2.创建poolSize大小的线程池
	 */
	public void createService() {
		destoryService(1000);
		executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * poolSize);
	}

	/**
	 * 在线程池中执行所有给定的任务并取回运行结果，使用默认超时时间
	 * 
	 * @throws InterruptedException
	 * @see invokeAll(List, long)
	 */
	public List<Result> invokeAll(List<Callable<Result>> tasks) throws InterruptedException {
		return invokeAll(tasks, DEFAULT_TASK_TIMEOUT * tasks.size());
	}

	/**
	 * 同execute方法 当前为有返回结果的运行
	 * 
	 * @param tasks
	 *            任务队列
	 * @param timeout
	 *            超时时间 毫秒
	 * @return
	 * @throws InterruptedException
	 */
	@SuppressWarnings("unchecked")
	public List<Result> invokeAll(List<Callable<Result>> tasks, long timeout) throws InterruptedException {
		List<Future<Result>> results = null;
		List<Result> resultList = new ArrayList<Result>();
		try {
			if (timeout < 0) {
				results = executorService.invokeAll(tasks);
			} else {
				results = executorService.invokeAll(tasks, timeout, TimeUnit.MILLISECONDS);
			}
			for (Future<Result> result : results) {
				resultList.add(result.get());
			}
		}
		catch (InterruptedException e) {
			e.printStackTrace();
			throw new InterruptedException(e.getMessage());
		}
		catch (ExecutionException e) {
			e.printStackTrace();
		}

		return resultList;
	}
}
